package com.kgo.log.logtools.file.watch;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSON;
import com.kgo.log.logtools.config.Socket;
import com.kgo.log.logtools.entity.LoggerInfoEntity;
import com.kgo.log.logtools.file.Dealfile;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;

/**
 * @author keepgoon
 * @Description: TODO
 * @date 2019/10/1620:19
 */
@Component
public class LoggerMonitor {
    public void loggerFile(String path){
        File file = FileUtil.file(path);
        //这里只监听文件或目录的修改事件
        WatchMonitor watchMonitor = WatchMonitor.create(file, WatchMonitor.ENTRY_MODIFY);
        watchMonitor.setWatcher(new Watcher(){
            @Override
            public void onCreate(WatchEvent<?> event, Path currentPath) {
                Object obj = event.context();
                Console.log("创建：{}-> {}", currentPath, obj);
            }

            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                Object obj = event.context();
                try {
//                    FileReader fileReader = new FileReader(currentPath.toString()+"/"+obj.toString());
//                    Charset fileCharset =  fileReader.getCharset();
//                    fileReader = new FileReader(currentPath.toString()+"/"+obj.toString(),fileCharset);
                    String result = Dealfile.getAllStr(currentPath.toString()+"/"+obj.toString());
                    LoggerInfoEntity loggerInfo = new LoggerInfoEntity();
                    loggerInfo.setLoggerContent(result);
                    loggerInfo.setFileName(obj.toString());
                    Socket.sendAll(JSON.toJSONString(loggerInfo));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Console.log("修改：{}-> {}", currentPath, obj);
            }

            @Override
            public void onDelete(WatchEvent<?> event, Path currentPath) {
                Object obj = event.context();
                Console.log("删除：{}-> {}", currentPath, obj);
            }

            @Override
            public void onOverflow(WatchEvent<?> event, Path currentPath) {
                Object obj = event.context();
                Console.log("Overflow：{}-> {}", currentPath, obj);
            }
        });

        watchMonitor.setMaxDepth(3);
        watchMonitor.start();
    }

    public static void main(String[] args) {
        LoggerMonitor loggerMonitor = new LoggerMonitor();
        loggerMonitor.loggerFile("D:\\log\\logtest");
    }
}
